#coding=utf-8

from xml.etree import ElementTree as ET
import re
import traceback

class T_XML_Exception(Exception):
    def __init__(self, args):
        super(T_XML_Exception, self).__init__(args)
        

def _error(msg):
    sys.stderr.write('%s\n'%msg)
    raise T_XML_Exception(msg)

class T_XML(object):
    def __init__(self, content):
        self.content = content
        self.subStrs = self.content.split('##')

    def t_xml(self):
        new_content = ''
        for subStr in self.subStrs:
            if self._check_in_type(subStr):
                subStr = self._deal_in_type(subStr)
                if subStr:
                    new_content += subStr
            else:
                new_content += subStr

        #生成整个条款的xml
        t_element = ET.Element('t', attrib={'choice':'op'})
        t_element.text = new_content

        xml = ET.tostring(t_element, encoding='utf-8', method=None)
        xml = self._replace_special_strs(xml)
        return xml

    def _replace_special_strs(self, xml):
        xml = xml.replace("&lt;", "<")
        xml = xml.replace("&gt;", ">")
        xml = xml.replace("&apos;", "\'")
        xml = xml.replace("&amp;", "&")
        xml = xml.replace("&quot;", "\"")
        return xml

    # 处理输入框类型，返回<in />
    def _deal_in_type(self, subStr):
        types = ['[]','{}','<>']
        type_tags = {'[]':'in', '{}':'in', '<>':'in_radio'}
        rules = subStr.split('_')

        items = []
        attrib = {}

        if len(rules) == 0:
            _error("ERROR:%s 无自定义格式" % self.content)
            return None
        if rules[0] not in types:
            _error("ERROR:%s 第一个标签非类型标签" % self.content)
            return None

        if rules[0] == '{}':
            underline = '0'
            attrib['underline'] = underline

        type_tag = type_tags[rules[0]]

        for rule in rules:
            rule = rule.strip()
            if '((' in rule and '))' in rule:
                tips = self._tips(rule)
                attrib['tips'] = tips
            if '(#' in rule and '#)' in rule:
                items = self._items(rule)
            if 'N' == rule:
                num_only = '1'
                attrib['num_only'] = num_only
            if 'R' == rule:
                readonly = '1'
                attrib['readonly'] = readonly



        type_element = ET.Element(type_tag, attrib=attrib)

        for i, item in enumerate(items):
            item_att = {}
            item_att['value'] = item
            if i == 0:
                item_att['checked'] = '1'
            ET.SubElement(type_element, 'item', attrib=item_att)

        return ET.tostring(type_element, encoding='utf-8', method=None)

    def _tips(self, rule):
        #表示in_tips
        rule = rule.strip()
        m = re.match(r'^\({2}(.*)\){2}$', rule, flags=0)

        if m:
            return m.group(1)
        return None

    def _items(self,rule):
        #(# #)表示items
        rule = rule.strip()
        m = re.match(r'^\(#(.*)#\)$', rule, flags=0)
        items_str = None
        if m:
             items_str = m.group(1)

        if items_str:
            return items_str.split('/')

        return None


    #判断是否为输入框类型
    def _check_in_type(self,subStr):
        types = ['[]','{}','<>']
        for tp in types:
            if tp in subStr:
                return True

        return False
